
import config from './config'
/*
选择图片或拍摄照片
function(count,fn)
count:选择图片数量
fn:成功回调函数
*/
// 使用相机
function Camera(count, fn) {
	uni.chooseImage({
		count: count,
		sizeType: ['original', 'compressed'],
		sourceType: ['camera'],
		success(res) {
			console.log(res, 111);
			// tempFilePath可以作为img标签的src属性显示图片
			const tempFilePaths = res.tempFilePaths;
			fn(tempFilePaths);
		}
	});
}

// 从相册选图
function Album(count, fn, tag) {
	uni.chooseImage({
		count: count,
		sizeType: ['original', 'compressed'],
		sourceType: ['album'],
		success(res) {

			// tempFilePath可以作为img标签的src属性显示图片
			const tempFilePaths = res.tempFilePaths;
			fn(tempFilePaths, tag);
		}
	});
}

// 使用相机和相册
function CameraAndAlbum(count, fn, tag) {
	uni.chooseImage({
		count: count,
		sizeType: ['original', 'compressed'],
		sourceType: ['camera', 'album'],
		success(res) {
			console.log(res, 'res');
			console.log(res.tempFiles[0].size,"size")
			let size=res.tempFiles[0].size
			if(size>=1048576*5){
				uni.$u.toast(`图片大小不能超过5M`);
				return
			}
			// tempFilePath可以作为img标签的src属性显示图片
			const tempFilePaths = res.tempFilePaths;
			fn(tempFilePaths, tag);
		}
	});
}

function upload(i,files, data, uploadSuccess, uploadFail, datas = {}) {
	const url = config.url + "/upload/file";
	uni.showLoading()
	//接口请求参数
	const postParams = {
		...datas,
	};
	let filePath;
	if (files[i].url !== undefined) {
		filePath = files[i].url;
	} else {
		filePath = files[i];
	}
	uni.uploadFile({
		url,
		filePath: filePath,
		name: "file",
		formData: postParams,
		header: {
			'Authorization':uni.getStorageSync("ap_token")
		},
		success: (res) => {
			res = JSON.parse(res.data);
			console.log(res, "upload res",res.data);
			if (res.code === 200) {
				i++;
				// 图片传完停止调用
				if (i >= files.length) {
					uni.hideLoading();
					data.push(res.data);
					uploadSuccess(data.join(","), res);
				} else {
					data.push(res.data);
					upload(i, files, data, uploadSuccess, uploadFail);
				}

				uni.showToast({
					title: `${res.msg}`,
					duration: 2000
				});
				uni.hideLoading();
				// uploadFail();
			}else{
				uni.showToast({
					title: `${res.msg}`,
					duration: 2000
				});
			}
		},
		fail: (e) => {
			uni.hideLoading();
			uploadFail(e);
		},
	});
}


const store = {
	upload: upload,
	chooseCamera: Camera,
	chooseAlbum: Album,
	CameraAndAlbum: CameraAndAlbum
};

export default store;
